<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantId"
            placeholder="请输入工厂"
            clearable
            @keyup.enter="search"
            filterable
          >
            <el-option
              v-for="plant in plantList"
              :key="plant.id"
              :label="plant.organizationCode"
              :value="plant.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="模板编号">
          <el-input
            v-model="searchParam.routingTemplateCode"
            placeholder="请输入模板编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="项目">
          <el-select
            v-model="searchParam.projectId"
            placeholder="请输入项目"
            clearable
            @keyup.enter="search"
            filterable
          >
            <el-option
              v-for="project in projectList"
              :key="project.id"
              :label="`${project.projectCode}-${project.projectName}`"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        :maxHeight="tableHeight"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="模板编号"
          prop="routingTemplateCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="模板说明"
          prop="routingTemplateName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="工厂"
          prop="plantId"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.plantCode }}
          </template>
        </el-table-column>
        <el-table-column
          label="项目"
          prop="projectId"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ `${scope.row.projectCode} - ${scope.row.projectName}` }}
          </template>
        </el-table-column>
        <!--<el-table-column
          label="制造环节角色"
          prop="manufacturingRole"
          min-width="110"
          align="center"
        >
          <template #default="scope">
            {{
              useDictionary("ManufacturingRole", scope.row.manufacturingRole)
            }}
          </template>
        </el-table-column>-->
        <el-table-column
          label="备注"
          prop="remarks"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="启用状态"
          prop="enabled"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="更新时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="更新人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="160" align="center">
          <template #default="scope">
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="查看"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialogdetail(scope.row)"
                ><i-ep-search />
              </el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="编辑"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialog(scope.row)"
                ><i-ep-edit
              /></el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="删除"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="deleteItem(scope.row.id)"
                ><i-ep-delete
              /></el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="复制"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="copyItem(scope.row.id)"
                ><i-ep-CopyDocument
              /></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mesroutingtemplate-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import {
  useTable,
  useDictionary,
  useComputeTableHeight,
} from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "MESMESROUTINGTEMPLATE",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesroutingtemplate/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  routingTemplateCode: "",
  plantId: "",
  projectId: "",
};

const deleteParam = {
  api: "/mes/mesroutingtemplate/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

// 定义tableHeight, 将计算注入dataCallBack回调中
const tableHeight = ref();
function dataCallBack(data: any) {
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
  }, 100);
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getPlantList();
  getProjectList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string, state?: number) {
  request({
    url: `/mes/mesroutingtemplate/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      if (state == 1) {
        addDialog.data.state = 1;
      }
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开工艺路线模板（新增表）表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改模板";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增模板";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}
/** 打开工艺路线模板（新增表）表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "模板详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/mes/mesroutingtemplate/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}
async function copyItem(id: any) {
  addDialog.title = "模板复制";
  getInfo(id, 1);
  addDialog.readvisible = false;
}
//工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
  searchParam.value.plantId = plantList.value[0].id;
};
const plantCode = (id: string) => {
  if (id) {
    const data = plantList.value.find((item) => item.id === id);
    return data.organizationCode;
  }
};
//项目列表
const projectList = ref([]);
const getProjectList = async () => {
  const { data } = await request({
    url: "mdm/mdmprojectinfo/getList",
    method: "post",
    data: { enable: 1, plantId: searchParam.value.plantId, deleted: 0 },
  });
  projectList.value = data;
};
// const projectCode = (id: string) => {
//   if (id) {
//     const data = projectList.value.find((item) => item.id === id);
//     return `${data.projectCode} - ${data.projectName}`;
//   }
// };
</script>
